import { useState, forwardRef, useImperativeHandle, useRef, useEffect } from 'react';
import { Modal, Form, Space, Button, Input, Upload, TreeSelect, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react';
import classify from '../../mobx/classify';
import { apiBaseUrl } from '../../utils/config';
// 将图片对象转换为base64字符串
const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
function ClassifyModal(props, ref) {
    // 类目封面图
    const [cover, setCover] = useState('');
    // 待更新类目id
    const [classifyId, setClassifyId] = useState(-1);
    // 控制模态框显示状态
    const [open, setOpen] = useState(false);
    const classifyFormRef = useRef(null);
    // 图片上传组件需要展示的图片列表数据
    const [fileList, setFileList] = useState([]);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const handleOk = () => {
        setTimeout(() => {
            setOpen(false);
        }, 3000);
    };
    const handleCancel = () => {
        // 关闭模态框
        setOpen(false);
        // 移除图片上传组件已选择的图片
        setFileList([]);
        // 重置待更新类目id
        setClassifyId(-1);
        // 重置表单
        classifyFormRef.current.resetFields();
    };
    // 给父组件暴漏方法
    useImperativeHandle(ref, () => {
        return {
            // 切换对话框组件显示状态
            toggleModal() {
                setOpen(open ? false : true);
            },
            // 接受待编辑类目数据
            getClassifyData(classifyData) {
                // 显示模态框组件
                setOpen(true);
                // 展示类目封面图
                const cover = classifyData.cover;
                if (cover) {
                    setFileList([{
                        url: apiBaseUrl + cover
                    }]);
                    // 更新cover
                    setCover(cover);
                }
                setClassifyId(classifyData.id);
                // 设置表单数据
                setTimeout(() => {
                    classifyFormRef.current.setFieldsValue({
                        ...classifyData
                    });
                }, 200);
            }
        }
    });

    const submit = async (values) => {
        // 更新类目封面图地址
        const { pid, name } = values;
        let res;
        if (classifyId > 0) {   // 更新
            res = await classify.updateClassify({ id: classifyId, pid, name, cover });
        } else {    // 新增
            res = await classify.addClassify({ pid, name, cover });
        }
        if (res.code === 200) {
            // 重置数据
            handleCancel();
            return message.success(res.msg);
        }
        message.error(res.msg);
    }

    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
    };
    // 绘制触发3次, 上传前, 上传中, 上传后(可以获取服务端返回的图片地址)
    const handleChange = ({ fileList: newFileList }) => {
        setFileList(newFileList);
        // 获取图片上传地址
        if (newFileList.length > 0 && newFileList[0].response) {
            setCover(newFileList[0].response.data);
        }
    };
    // 关闭图片预览模态框
    const previewHandleCancel = () => setPreviewOpen(false);
    // 移除已选择的图片
    const handleUploadRemove = () => {
        setCover('');
    }
    // 图片上传按钮
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                选择图片
            </div>
        </div>
    );

    useEffect(() => {
        // 请求类目列表数据
        classify.getClassifyList();
    }, []);
    return (
        <>
            <Modal
                open={open}
                title={classifyId > 0 ? '更新类目' : '新增类目'}
                onOk={handleOk}
                onCancel={handleCancel}
                footer={null}
                width={'60%'}
            >
                <Form ref={classifyFormRef} onFinish={submit} onReset={handleCancel}>

                    <Form.Item label="上级类目" name='pid' rules={[
                        { required: true, message: '请选择上级类目!' }
                    ]}>
                        <TreeSelect
                            fieldNames={{ label: 'name', value: 'id' }}
                            style={{ width: '100%' }}
                            placeholder="上级类目"
                            allowClear
                            treeDefaultExpandAll
                            treeData={classify.classifyList}
                        />
                    </Form.Item>

                    <Form.Item name="name" label="类目名称" rules={[{
                        required: true,
                        message: "请输入类目名称",
                        type: 'string'
                    }]}>
                        <Input placeholder="类名名称"></Input>
                    </Form.Item>
                    <Form.Item name="cover" label="类目封面"
                        rules={[
                            {
                                required: true,
                                // 自定义表单校验规则
                                validator: async () => {
                                    if (!cover) {
                                        throw new Error('请选择封面图片!');
                                    }
                                },
                                message: '请选择封面图片!!!'
                            }]}>
                        <>
                            <Upload
                                action="/admin/imgUpload"
                                listType="picture-card"
                                fileList={fileList}
                                onPreview={handlePreview}
                                onChange={handleChange}
                                onRemove={handleUploadRemove}
                                name="img"
                            >
                                {fileList.length >= 8 ? null : uploadButton}
                            </Upload>
                            {/* 图片预览 */}
                            <Modal open={previewOpen} title='预览' footer={null} onCancel={previewHandleCancel}>
                                <img
                                    alt="example"
                                    style={{
                                        width: '100%',
                                    }}
                                    src={previewImage}
                                />
                            </Modal>

                        </>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 19 }}>
                        <Space>
                            <Button htmlType='submit' type="primary">确认提交</Button>
                            <Button htmlType='reset' type="primary" danger>取消</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}
export default observer(forwardRef(ClassifyModal));